﻿using Appliaction.Dto.Inv;
using Domain.Entitys.Base_Manage;
using Domain.Entitys.Inv;
using Domain.IRepositorys.Inv;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace EFCore.Repositorys.Inv
{
    public class Inv_othwrRepository : IInv_othwrRepository
    {
        private readonly MyDbContext myDbContext;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="myDbContext"></param>
        public Inv_othwrRepository(MyDbContext myDbContext)
        {
            this.myDbContext = myDbContext;
        }
        /// <summary>
        /// 获取字典值
        /// </summary>
        /// <param name="dict_value"></param>
        /// <param name="dict_type"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<string> dict_data_Select(string dict_value, string dict_type)
        {
            var data = await myDbContext.Sys_Dict_Data.Where(e => e.Dict_value == dict_value && e.Dict_type == dict_type && e.Del_flag == '0').FirstOrDefaultAsync();
            if (data == null)
            {
                return "";
            }
            return data.Dict_label;
        }

        /// <summary>
        /// 分页查询
        /// </summary>
        /// <param name="searchKeyword"></param>
        /// <param name="othoutord_type"></param>
        /// <param name="currentPage"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public List<othwrSelectDto> GetOthwrWithDetailsAsync(string searchKeyword, string othoutord_type, int currentPage, int pageSize)
        {
            // 使用 IQueryable 延迟构建查询
            IQueryable<Inv_othwr> query = myDbContext.inv_othwr;

            // 条件1: 根据入库类型筛选（如果提供了）
            if (!string.IsNullOrEmpty(othoutord_type)) // 假设0表示“全部”或无效值
            {
                query = query.Where(x => x.Othwr_type == othoutord_type);
            }

            // 条件2: 根据关键字搜索（如果提供了）
            if (!string.IsNullOrEmpty(searchKeyword))
            {
                query = query.Where(x => x.Othwr_code.Contains(searchKeyword));
            }

            // 条件3: 删除标志为未删除（del_flag == '0'）
            query = query.Where(x => x.del_flag == '0').OrderByDescending(d => d.Create_time);
 
        // 分页和投影
        var result = query
                .Skip((currentPage - 1) * pageSize)
                .Take(pageSize)
                .Select(main => new othwrSelectDto
                {
                    Othwr_id = main.Othwr_id,
                    othwr_type = main.Othwr_type,
                    othwr_code = main.Othwr_code,
                    warehouse_code = main.Warehouse_code,
                    warehouse_name = main.Warehouse_name,
                    othwr_audit_statua = main.othwr_audit_statua,
                    Othwr_status = main.Othwr_status,
                    Othwr_wkeep = main.Othwr_wkeep,
                    Othwr_time = main.Othwr_time,
                    zone_code= main.Zone_code,
                    zone_name= main.Zone_name,
                    othwr_audit_opinion= main.othwr_audit_opinion,
                    othwr_code_Associated=main.othwr_code_Associated,
                    Details = main.Details.Select(detail => new othwrSelectDto.OthwrDetailInfo
                    {
                        othwr_id = detail.Othwr_id,
                        pro_name = detail.Pro_name,
                        pro_code = detail.Pro_code,
                        pro_brand = detail.Pro_brand,
                        unitmeas_id = detail.unitmeas_id,
                        othwrproddtl_numder = detail.Othwrproddtl_numder,
                        pro_model = detail.Pro_model,
                        stock_entry_no=detail.stock_entry_no,
                        location_code=detail.location_code,
                    }).ToList()
                })
                .ToList();

            return result;

        }
        /// <summary>
        /// 查询总数
        /// </summary>
        /// <param name="searchKeyword"></param>
        /// <param name="othoutord_type"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public Task<int> GetTotalCountAsync(string searchKeyword, string othoutord_type)
        {
            var query = myDbContext.inv_othwr.AsQueryable();

            query=query.Where(x => x.del_flag == '0');  

            // 条件1: 入库类型筛选（如果提供了）
            if (!string.IsNullOrEmpty(othoutord_type))
            {
                query = query.Where(x => x.Othwr_type == othoutord_type);
            }

            // 条件2: 关键字搜索（如果提供了）
            if (!string.IsNullOrEmpty(searchKeyword))
            {
                query = query.Where(x => x.Othwr_code.Contains(searchKeyword));

            }

            // 统计总数
            return query.CountAsync();
        }


        /// <summary>
        /// 查询库存调拨表
        /// </summary>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>

        public List<Inv_othwr> Inv_othwrall_qty()
        {

            var result = myDbContext.inv_othwr.Where(e => e.del_flag == '0').ToList();
            return result;
        }
        /// <summary>
        ///  查询库存盘盈单号
        /// </summary>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public List<Inv_othwr> Inv_othwrall_trf()
        {
            var result_try = myDbContext.inv_othwr.Where(e => e.del_flag == '0').ToList();
            return result_try;
        }

        /// <summary>
        /// 根据其他入库单查看详情
        /// </summary>
        /// <param name="Othwr_code"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<List<Inv_othwrproddtl>> inv_OthwrproddtlSelect(string Othwr_code)
        {
            var Inv_othwr = await myDbContext.inv_othwr.Where(e => e.Othwr_code == Othwr_code && e.del_flag == '0').FirstOrDefaultAsync();
            if (Inv_othwr == null)
            {
                throw new Exception("仓库不存在");
            }
            var Inv_othwrproddtl = await myDbContext.inv_othwrproddtl.Where(e => e.Othwr_id == Inv_othwr.Othwr_id).ToListAsync();


            return Inv_othwrproddtl;
        }
        /// <summary>
        /// 查询id,添加详情
        /// </summary>
        /// <param name="otgwr_code"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<int> inv_OthwrproddtlSelect_id(string otgwr_code)
        {
            var entity = await myDbContext.inv_othwr
            .FirstOrDefaultAsync(e => e.Othwr_code == otgwr_code && e.del_flag == '0');

            if (entity == null)
            {
                throw new Exception("未找到对应的仓库记录");
            }

            return entity.Othwr_id;
        }

        /// <summary>
        /// 查询数据字典字典值
        /// </summary>
        /// <param name="dict_value"></param>
        /// <param name="dict_type"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<List<Sys_Dict_Data>> inv_othwr_SelectData(string dict_value, string dict_type)
        {
            var data = await myDbContext.Sys_Dict_Data.Where(e => e.Dict_value == dict_value && e.Dict_type == dict_type && e.Del_flag == '0').ToListAsync();
            return data;
        }
        /// <summary>
        /// 查询入库单的信息
        /// </summary>
        /// <param name="Othwr_code"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<List<Inv_othwr>> inv_othwr_SelectWeahouse(string Othwr_code)
        {
            var Inv_othwr = await myDbContext.inv_othwr.Where(e => e.Othwr_code == Othwr_code && e.del_flag == '0').ToListAsync();
            if (Inv_othwr == null)
            {
                throw new Exception("仓库不存在");
            }
            return Inv_othwr;
        }



        /// <summary>
        /// 添加其他入库单
        /// </summary>
        /// <param name="inv_Othwr"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<int> Inv_othwr_Insert(Inv_othwr inv_Othwr)
        {
            await myDbContext.inv_othwr.AddAsync(inv_Othwr);
            return await myDbContext.SaveChangesAsync();
        }
        /// <summary>
        /// 添加入库添加其他详情表
        /// </summary>
        /// <param name="inv_Othwrproddtl"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<int> Inv_othproddetails(List<Inv_othwrproddtl> entities)
        {
            await myDbContext.inv_othwrproddtl.AddRangeAsync(entities);
            return await myDbContext.SaveChangesAsync();
        }
        /// <summary>
        /// 删除入库单
        /// </summary>
        /// <param name="othwr_id"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<int> Inv_othwr_delete(int othwr_id)
        {
            var othwr = await myDbContext.inv_othwr.Where(x => x.Othwr_id == othwr_id).FirstOrDefaultAsync();
            if (othwr == null) {

                throw new Exception("未找到对应的入库单"); 
            }
            othwr.del_flag = '1';
            return await myDbContext.SaveChangesAsync();
        }   

        /// <summary>
        /// 修改其他审核状态
        /// </summary>
        /// <param name="othwr_code"></param>
        /// <param name="Othwr_audit_by"></param>
        /// <param name="Othwr_audit_time"></param>
        /// <param name="othwr_audit_statua"></param>
        /// <param name="othwr_audit_opinion"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<int> Inv_othwr_examineUpdate(Inv_othwr othwrupdate)
        {
            var othwr = await myDbContext.inv_othwr.Where(e => e.Othwr_code == othwrupdate.Othwr_code).FirstOrDefaultAsync();
            if (othwr == null)
            {

                throw new Exception("未找到对应的入库单");
            }
            // 更新审核信息
            othwr.Othwr_audit_by = othwrupdate.Othwr_audit_by;
            othwr.Othwr_audit_time = othwrupdate.Othwr_audit_time; // 如果传的是字符串
            othwr.othwr_audit_statua = othwrupdate.othwr_audit_statua;
            othwr.othwr_audit_opinion = othwrupdate.othwr_audit_opinion;

            // 保存更改
            return await myDbContext.SaveChangesAsync();

        }
        /// <summary>
        /// 修改入库单和入库单详情
        /// </summary>
        /// <param name="inv_Othwr"></param>
        /// <param name="entities"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<int> Inv_othwr_Update(Inv_othwr inv_Othwr, List<Inv_othwrproddtl> entities)
        {
            using var transaction = await myDbContext.Database.BeginTransactionAsync();
            try
            {
                // 1. 更新主表信息
                var existingOrder = await myDbContext.inv_othwr
                    .FirstOrDefaultAsync(o => o.Othwr_id == inv_Othwr.Othwr_id);

                if (existingOrder == null)
                {
                    throw new Exception($"入库单 {inv_Othwr.Othwr_code} 不存在");
                }

                // 只更新允许修改的字段
                existingOrder.Othwr_type = inv_Othwr.Othwr_type;
                existingOrder.Warehouse_code = inv_Othwr.Warehouse_code;
                existingOrder.Warehouse_name = inv_Othwr.Warehouse_name;
                existingOrder.Zone_code = inv_Othwr.Zone_code;
                existingOrder.Zone_name = inv_Othwr.Zone_name;
                existingOrder.Othwr_status = inv_Othwr.Othwr_status;
                existingOrder.Othwr_wkeep = inv_Othwr.Othwr_wkeep;
                existingOrder.Othwr_time = inv_Othwr.Othwr_time;
                existingOrder.Update_by = inv_Othwr.Update_by;
                existingOrder.Update_time = inv_Othwr.Update_time;

                myDbContext.Update(existingOrder);
                await myDbContext.SaveChangesAsync();

                // 2. 获取现有明细
                var existingDetails = await myDbContext.inv_othwrproddtl
                    .Where(d => d.Othwr_id == inv_Othwr.Othwr_id)
                    .ToListAsync();

                // 3. 识别三类记录
                var toAdd = new List<Inv_othwrproddtl>();
                var toUpdate = new List<Inv_othwrproddtl>();
                var toDeleteIds = new List<int>();

                // 处理传入的新明细
                foreach (var newItem in entities)
                {
                    // 新增记录：ID为0或不在现有明细中
                    if (newItem.othwrproddtl_id == 0 ||
                        !existingDetails.Any(d => d.othwrproddtl_id == newItem.othwrproddtl_id))
                    {
                        toAdd.Add(newItem);
                    }
                    // 更新记录：ID存在且字段有变化
                    else
                    {
                        var existingItem = existingDetails
                            .First(d => d.othwrproddtl_id == newItem.othwrproddtl_id);

                        if (IsModified(existingItem, newItem))
                        {
                            toUpdate.Add(newItem);
                        }
                    }
                }

                // 识别需要删除的记录
                toDeleteIds = existingDetails
                    .Where(d => !entities.Any(e => e.othwrproddtl_id == d.othwrproddtl_id))
                    .Select(d => d.othwrproddtl_id)
                    .ToList();

                // 4. 执行差异化操作
                // 4.1 删除被移除的明细
                if (toDeleteIds.Any())
                {
                    var deleteItems = existingDetails
                        .Where(d => toDeleteIds.Contains(d.othwrproddtl_id))
                        .ToList();

                    myDbContext.RemoveRange(deleteItems);
                }

                // 4.2 更新变化的明细
                foreach (var item in toUpdate)
                {
                    var existingItem = existingDetails
                        .First(d => d.othwrproddtl_id == item.othwrproddtl_id);

                    // 更新允许修改的字段
                    existingItem.Pro_name = item.Pro_name;
                    existingItem.Pro_code = item.Pro_code;
                    existingItem.Pro_brand = item.Pro_brand;
                    existingItem.unitmeas_id = item.unitmeas_id;
                    existingItem.Othwrproddtl_numder = item.Othwrproddtl_numder;
                    existingItem.Inventory_numder = item.Inventory_numder;
                    existingItem.Pro_model = item.Pro_model;
                    existingItem.location_code = item.location_code;
                    existingItem.location_name = item.location_name;
                    existingItem.pro_cost_price = item.pro_cost_price;
                    existingItem.pro_sale_price = item.pro_sale_price;

                    myDbContext.Update(existingItem);
                }

                // 4.3 添加新明细
                foreach (var item in toAdd)
                {
                    item.Othwr_id = inv_Othwr.Othwr_id;
                    item.Othwrproddtl_time = DateTime.Now;
                    item.Othwrproddtl_yuan = inv_Othwr.Othwr_wkeep;

                    await myDbContext.AddAsync(item);
                }

                await myDbContext.SaveChangesAsync();
                await transaction.CommitAsync();

                return 1;
            }
            catch (Exception ex)
            {
                await transaction.RollbackAsync();
                // 记录日志
                // logger.LogError(ex, "更新入库单失败");
                return 0;
            }
        }

        // 辅助方法：检查明细是否被修改
        private bool IsModified(Inv_othwrproddtl existing, Inv_othwrproddtl updated)
        {
            return existing.Pro_name != updated.Pro_name ||
                   existing.Pro_code != updated.Pro_code ||
                   existing.Pro_brand != updated.Pro_brand ||
                   existing.unitmeas_id != updated.unitmeas_id ||
                   existing.Othwrproddtl_numder != updated.Othwrproddtl_numder ||
                   existing.Inventory_numder != updated.Inventory_numder ||
                   existing.Pro_model != updated.Pro_model ||
                   existing.location_code != updated.location_code ||
                   existing.location_name != updated.location_name ||
                   existing.pro_cost_price != updated.pro_cost_price ||
                   existing.pro_sale_price != updated.pro_sale_price;
        }
        /// <summary>
        /// 修改其他入库单的状态
        /// </summary>
        /// <param name="othwr_code"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<int> Inv_othwr_Update_othwr_staus(string othwr_code)
        {
           
            // 1. 查询其他入库单得到 Id
            var othwr = await myDbContext.inv_othwr
                .Where(e => e.Othwr_code == othwr_code && e.del_flag == '0')
                .FirstOrDefaultAsync();

            if (othwr == null)
            {
                throw new Exception("未找到对应的入库单");
            }

            // 2. 查询该入库单的所有明细
            var details = await myDbContext.inv_othwrproddtl
                .Where(d => d.Othwr_id == othwr.Othwr_id)
                .ToListAsync();

        
            foreach (var detail in details)
            {
              
                var trfproddtl = await myDbContext.inv_trfproddtl
                    .Where(t => t.Pro_code == detail.Pro_code && t.stock_entry_no == detail.stock_entry_no)
                    .FirstOrDefaultAsync();

                if (trfproddtl != null)
                {
                  
                    if (trfproddtl.Inventory_numder == detail.Othwrproddtl_numder)
                    {
                     
                        othwr.Othwr_status = 1;
                        await myDbContext.SaveChangesAsync();
                        return othwr.Othwr_status;
                    } else if (trfproddtl.Inventory_numder!= detail.Othwrproddtl_numder) {
                        othwr.Othwr_status = 2;
                        await myDbContext.SaveChangesAsync();
                        return othwr.Othwr_status;
                    }
                }
            }
            // 如果没有找到匹配的记录，返回当前状态
            return othwr.Othwr_status;
        }


        /// <summary>
        /// 根据入库单号去修改入库单的状态--判断,期初
        /// </summary>
        /// <param name="othwr_code"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<int> Inv_othwr_Update_othwr_staus_pd(string othwr_code)
        {
            var othwr = await myDbContext.inv_othwr
          .Where(e => e.Othwr_code == othwr_code && e.del_flag == '0')
          .FirstOrDefaultAsync();

            if (othwr == null)
            {
                throw new Exception("未找到对应的入库单");
            }


            othwr.Othwr_status = 1;
            return await myDbContext.SaveChangesAsync();
        }
    }

    }

    
    

